const redis = require("redis");

//创建
async function createClient(ip, port, password=null, db=0) {
    let client = redis.createClient({
        url: `redis://${ip}:${port}`,
        password: password,
        database: db
    });
    try {
        await client.connect();
        //只设置一次过期时间
        client.setExpireOnce = async function(k, sec) {
            try {
                const nowSec = await this.ttl(k);
                if (nowSec <= 0) {
                    await client.expire(k, sec);
                    return sec;
                } else {
                    return nowSec;
                }
            } catch (error) {
                if (global.log) {
                    global.log.error(err);
                } else {
                    console.error(err);
                }
                return 0;
            }
        }
        //如果没有过期则刷新过期时间
        client.refreshExpire = async function(k, sec) {
            try {
                const nowSec = await this.ttl(k);
                if (nowSec > 0 && nowSec < sec/2) {
                    await client.expire(k, sec);
                }
            } catch (error) {
                if (global.log) {
                    global.log.error(err);
                } else {
                    console.error(err);
                }
            }
        }
        return client;
    } catch (error) {
        if (global.log) {
            global.log.error(error);
        } else {
            console.error(error);
        }
        return null;
    }
}

module.exports = createClient;
